package com.zy.chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zy.chat.entity.Follow;
import com.zy.chat.entity.UserInfo;
import com.zy.chat.entity.UserLogin;
import com.zy.chat.mapper.FollowMapper;
import com.zy.chat.service.IFollowService;
import com.zy.chat.service.UserService;
import com.zy.chat.util.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.zy.chat.util.RedisContants.*;


@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {


    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserService userService;
    @Override
    public Boolean isFollow(String  followUser) {
        String username= UserHolder.getUser().getUsername();
        Long count = query().eq("username", username)
                .eq("follow_username", followUser).count();
        return  count>0;
    }

    @Override
    public Boolean follow(String followUser, Boolean isFollow) {
        String username = UserHolder.getUser().getUsername();
        String key=FOLLOWS+followUser;
        if (!isFollow) {
            Follow follow=new Follow();
            follow.setFollowUsername(followUser).setUsername(username);
            boolean isSuccess = save(follow);
            if(isSuccess){
                redisTemplate.opsForSet().add(key,username);
            }
            return true;
        }else{
            boolean isSuccess = remove(new QueryWrapper<Follow>()
                    .eq("username", username)
                    .eq("follow_username", followUser));
            if(isSuccess){
                System.out.println("是否存在:"+redisTemplate.opsForSet().isMember(key, followUser));
                redisTemplate.opsForSet().remove(key,followUser);
            }
            return false;
        }


    }
    public List<UserInfo> followCommon(String followUser ){
        String username = UserHolder.getUser().getUsername();
        String key1=FOLLOWS+username;
        String key2=FOLLOWS+followUser;
        Set<String> intersect = redisTemplate.opsForSet().intersect(key1, key2);
        if(intersect==null||intersect.isEmpty()){
            return Collections.emptyList();
        }
        List<String> ns = intersect.stream().collect(Collectors.toList());
        List<UserInfo> userList = new ArrayList<>();

        ns.forEach(s -> {
            UserInfo user = userService.query().eq("username",username).one();
            if (user != null) {
                userList.add(user);
            }
        });
        return userList;
    }
}
